import config from './config'
import { LoginUser } from './interfaces'
import CryptoJS from 'crypto-js'

export const UUID = (prefix = '') => prefix + Date.now().toString(36) + '-' + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36)

const login_user_map = new Map<string | undefined, LoginUser>()
const user_token_map = new Map<string, string>()
export const setUser = function (key: string, user: LoginUser) {
  login_user_map.set(key, user)
  user_token_map.set(user.username, user.token)
}
export const getUser = function (key: string) {
  return login_user_map.get(key)
}
export const deleteUser = function (key: string) {
  const user = getUser(key)
  login_user_map.delete(key)
  user_token_map.delete(user?.username)
}
export const getUserToken = function (username: string) {
  return user_token_map.get(username)
}

export const DEFAULT_ENCRYPT_KEY = '@DEFAULT_ENCRYPT'
/** 加密服务端返回数据 */
export const doEncode = (result: any, token: string | null) => {
  const { encrypt } = config.client || {}
  if (encrypt) {
    const key = CryptoJS.enc.Utf8.parse(token || DEFAULT_ENCRYPT_KEY)
    const iv = CryptoJS.enc.Utf8.parse('ABCDEF0123456789')
    const srcs = CryptoJS.enc.Utf8.parse(JSON.stringify(result));
    return {
      __content: CryptoJS.AES.encrypt(srcs, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      }).ciphertext.toString().toUpperCase(),
    }
  }
  return result
}
/** 解密客户端提交数据 */
export const doDecode = (body: any, token: string | null) => {
  const { encrypt } = config.client || {}
  if (body && body.__content && encrypt) {
    const key = CryptoJS.enc.Utf8.parse(token || DEFAULT_ENCRYPT_KEY)
    const iv = CryptoJS.enc.Utf8.parse('ABCDEF0123456789')
    const encryptedHexStr = CryptoJS.enc.Hex.parse(body.__content);
    const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    const jsonStr = CryptoJS.AES.decrypt(
      srcs, key, {
          iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7,
      }
  ).toString(CryptoJS.enc.Utf8).toString()
    return JSON.parse(jsonStr)
  }
  return body
}